
package com.ny.service;

import com.ny.dao.UserDao;
import com.ny.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    // 查询所有
    @Transactional(readOnly = true)
    public List<User> getAllUsers() {
        return userDao.findAll();
    }

    // 根据 ID 查询
    @Transactional(readOnly = true)
    public User getUserById(Integer id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("用户ID不能为空且必须大于0");
        }
        return userDao.findById(id);
    }

    // 新增用户
    @Transactional
    public boolean createUser(String name, String password) {
        if (!StringUtils.hasText(name) || !StringUtils.hasText(password)) {
            return false;
        }
        User user = new User(name, password);
        int rows = userDao.insert(user);
        return rows > 0;
    }

    // 更新用户
    @Transactional
    public boolean updateUser(Integer id, String name, String password) {
        if (id == null || id <= 0) {
            return false;
        }
        User user = new User();
        user.setId(id);
        user.setName(StringUtils.hasText(name) ? name : null);
        user.setPassword(StringUtils.hasText(password) ? password : null);

        int rows = userDao.update(user);
        return rows > 0;
    }

    // 删除用户
    @Transactional
    public boolean deleteUser(Integer id) {
        if (id == null || id <= 0) {
            return false;
        }
        int rows = userDao.deleteById(id);
        return rows > 0;
    }
}